package MD.NJavaUnionAd;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import MD.NJavaBase.IAdCallback;
import MD.NJavaBase.IBanner;
import MD.NJavaBase.ICallbackLight;
import MD.NJavaBase.NJavaBase;
import android.util.Log;

public class UnionNativeExpress implements IBanner, TTAdNative.NativeExpressAdListener {
    static String Tag = "UnionNativeExpress";

    public UnionNativeExpress(int priority)
    {
        m_Priority = priority;
        Activity activity = NJavaBase.getActivity();
        String UnionNativeExpressId = "";
        try {
            ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(
                    activity.getPackageName(), PackageManager.GET_META_DATA
            );

            UnionNativeExpressId = appInfo.metaData.getString("UnionNativeExpressId") ;
            if(UnionNativeExpressId.length()>0 && UnionNativeExpressId.charAt(0)=='#')
                UnionNativeExpressId = UnionNativeExpressId.substring(1);

        } catch (PackageManager.NameNotFoundException e) {
            Log.e(Tag, "init error!");
            e.printStackTrace();
        }

        m_UnionNativeExpressId = UnionNativeExpressId;

        m_AdNative= TTAdSdk.getAdManager().createAdNative(NJavaBase.getActivity());

        //强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdSdk.getAdManager().requestPermissionIfNecessary(activity);


        //等待一会儿才允许装载banner
        {
            Timer reloadTimer = new Timer();// 实例化Timer类
            class overTimeTask extends TimerTask {
                public void run() {
                    class reloadRunnable implements Runnable {
                        @Override
                        public void run() {
                            m_Initdone = true;
                        }
                    }
                    NJavaBase.getActivity().runOnUiThread(new reloadRunnable());
                    this.cancel();
                }
            }
            reloadTimer.schedule(new overTimeTask(), 5000);// 毫秒
        }
    }


    //是否已经初始化完毕，可以开始加载
    public boolean isInitialized() {
        return m_Initdone;
    }

    //广告平台的名称
    public String adName() { return "UnionAd"; }

    //是否已经过期
    public boolean isInvalidated()
    {
        return this.getView()==null;
    }

    //预装 回调0表示预装成功 99表示预装失败
    public void reloadAd(IAdCallback callBack)
    {
        if(m_Loading ) return;
        //if(m_View==null)//没有缓存成功
        //{
        m_Loading = true;
        m_Callback = callBack;
        this.load();
            /*
        }else{ //已经是装载成功的
            callBack.reCall(new Integer(0));
        }*/
    }

    //是否需要由loader去检查加载超时
    public boolean needCheckLoadOvertime() { return true;}

    //获取控件
    public View getView()
    {
        return m_View;
    }

    //优先级，值越大越优先
    public int getPriority()
    {
        return m_Priority;
    }



    void load()
    {
        //销毁掉过时的对象
        {
            for (int i = 0; i < m_TTAdList.size(); ) {
                TTNativeExpressAd ad = (TTNativeExpressAd) m_TTAdList.get(i);
                if (ad.getExpressAdView() == null) {
                    ad.destroy();
                    m_TTAdList.remove(i);
                } else
                    i++;
            }
            while (m_TTAdList.size() > 10) {
                TTNativeExpressAd ad = (TTNativeExpressAd) m_TTAdList.get(0);
                ad.destroy();
                m_TTAdList.remove(0);
            }
        }

        Log.e(Tag, "load #1");

        WindowManager wm = (WindowManager) NJavaBase.getActivity().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;// 屏幕宽度（像素）
        //int height= dm.heightPixels; // 屏幕高度（像素）
        float density = dm.density;//屏幕密度（0.75 / 1.0 / 1.5）
        //int densityDpi = dm.densityDpi;//屏幕密度dpi（120 / 160 / 240）

        //屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width/density);//屏幕宽度(dp)
        //int screenHeight = (int)(height/density);//屏幕高度(dp)

        float expressViewWidth = screenWidth;
        float expressViewHeight = 0;//自适应
        //Random random=new Random();
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(m_UnionNativeExpressId)
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(expressViewWidth,expressViewHeight) //必填：期望个性化模板广告view的size,单位dp
                //.setImageAcceptedSize(640,320) //这个参数设置即可，不影响个性化模板广告的size
                .build();

        //m_NativeList
        m_AdNative.loadNativeExpressAd(adSlot, this);

        Log.e(Tag, "load setName");
    }

    @Override
    public void onError(int code, String message) {
        m_Loading = false;
        Log.e(Tag, "load error : " + code + ", " + message);
        m_Callback.onError(  String.valueOf(-98));
        //mExpressContainer.removeAllViews();
    }

    @Override
    public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {

        if (ads == null || ads.size() == 0){
            m_Loading = false;
            Log.e(Tag, "onNativeExpressAdLoad error #1 ");
            m_Callback.onError(  String.valueOf(-99));
            return;
        }

        m_TTAdList.add(ads.get(0));
        bindAdListener();
        ((TTNativeExpressAd)m_TTAdList.get(m_TTAdList.size()-1)).render();//调用render开始渲染广告
    }


    //绑定广告行为
    private void bindAdListener() {
        final TTNativeExpressAd ad = ((TTNativeExpressAd)m_TTAdList.get(m_TTAdList.size()-1));

        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
                //TToast.show(mContext, "广告被点击");
            }

            @Override
            public void onAdShow(View view, int type) {
                //TToast.show(mContext, "广告展示");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                //Log.e("ExpressView","render fail:"+(System.currentTimeMillis() - startTime));
                //TToast.show(mContext, msg+" code:"+code);
                Log.e(Tag,  msg+" code:"+code);
                m_Loading = false;
                m_Callback.onError(String.valueOf(code)); //reCall( new Integer(99));
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                m_Loading = false;
                Log.e(Tag, "渲染成功");
                //返回view的宽高 单位 dp
                //TToast.show(mContext, "渲染成功");
                //在渲染成功回调时展示广告，提升体验
                //mExpressContainer.removeAllViews();
                //mExpressContainer.addView(view);
                m_View = view;
                m_Callback.onLoad();//reCall( new Integer(0));
            }
        });

        //dislike设置
        bindDislike(ad, false);
  /*
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD){
            return;
        }


        //可选，下载监听设置
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
                TToast.show(NativeExpressActivity.this, "点击开始下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                if (!mHasShowDownloadActive) {
                    mHasShowDownloadActive = true;
                    TToast.show(NativeExpressActivity.this, "下载中，点击暂停", Toast.LENGTH_LONG);
                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                TToast.show(NativeExpressActivity.this, "下载暂停，点击继续", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                TToast.show(NativeExpressActivity.this, "下载失败，点击重新下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onInstalled(String fileName, String appName) {
                TToast.show(NativeExpressActivity.this, "安装完成，点击图片打开", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                TToast.show(NativeExpressActivity.this, "点击安装", Toast.LENGTH_LONG);
            }
        });
        */
    }
    /**
     * 设置广告的不喜欢，开发者可自定义样式
     * @param ad
     * @param customStyle 是否自定义样式，true:样式自定义
     */
    private void bindDislike(TTNativeExpressAd ad, boolean customStyle) {
        /*
        if (customStyle) {
            //使用自定义样式
            List<FilterWord> words = ad.getFilterWords();
            if (words == null || words.isEmpty()) {
                return;
            }

            final DislikeDialog dislikeDialog = new DislikeDialog(this, words);
            dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
                @Override
                public void onItemClick(FilterWord filterWord) {
                    //屏蔽广告
                    TToast.show(mContext, "点击 " + filterWord.getName());
                    //用户选择不喜欢原因后，移除广告展示
                    mExpressContainer.removeAllViews();
                }
            });
            ad.setDislikeDialog(dislikeDialog);
            return;
        }*/

        //使用默认个性化模板中默认dislike弹出样式
        ad.setDislikeCallback(NJavaBase.getActivity(), new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onSelected(int position, String value) {
                //TToast.show(mContext, "点击 " + value);
                //用户选择不喜欢原因后，移除广告展示
                //mExpressContainer.removeAllViews();
                if(m_View!=null)
                {
                    ViewGroup vg = (ViewGroup) m_View.getParent();
                    vg.removeView(m_View);

                    m_View = null;
                }
            }

            @Override
            public void onCancel() {
                //TToast.show(mContext, "点击取消 ");
            }
        });
    }

    int m_Priority;
    String m_UnionNativeExpressId;
    //TTAdNative m_AdNative;
    boolean m_Initdone = false;
    boolean m_Loading = false;
    IAdCallback m_Callback;
    //TTNativeExpressAd mTTAd;
    ArrayList m_TTAdList = new ArrayList();
    //ArrayList m_NativeList = new ArrayList();
    View m_View;
    TTAdNative m_AdNative;
}
